import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:provider/provider.dart';
import 'dart:async';
import '../l10n/app_localizations.dart';
import '../services/log_service.dart';
import '../providers/settings_provider.dart';

class ConnectionLogScreen extends StatefulWidget {
  const ConnectionLogScreen({super.key});

  @override
  State<ConnectionLogScreen> createState() => _ConnectionLogScreenState();
}

class _ConnectionLogScreenState extends State<ConnectionLogScreen> {
  final LogService _logService = LogService();
  final ScrollController _scrollController = ScrollController();
  
  LogLevel? _filterLevel;
  String? _filterCategory;
  bool _autoScroll = true;
  StreamSubscription<LogEntry>? _logSubscription;
  
  // 用于优化性能的局部状态
  List<LogEntry> _cachedFilteredLogs = [];
  Timer? _rebuildTimer;

  @override
  void initState() {
    super.initState();
    _updateCachedLogs();
    
    // 监听新日志，使用防抖优化性能
    _logSubscription = _logService.logStream.listen((_) {
      // 使用 Timer 防抖，避免频繁重建
      _rebuildTimer?.cancel();
      _rebuildTimer = Timer(const Duration(milliseconds: 100), () {
        if (mounted) {
          setState(() {
            _updateCachedLogs();
          });
          
          // 自动滚动到底部
          if (_autoScroll && _scrollController.hasClients) {
            _scrollController.animateTo(
              _scrollController.position.maxScrollExtent,
              duration: const Duration(milliseconds: 200),
              curve: Curves.easeOut,
            );
          }
        }
      });
    });
    
    // 监听滚动，自动检测是否在底部
    _scrollController.addListener(_handleScroll);
  }

  @override
  void dispose() {
    _logSubscription?.cancel();
    _rebuildTimer?.cancel();
    _scrollController.dispose();
    super.dispose();
  }

  void _handleScroll() {
    if (_scrollController.hasClients) {
      final isAtBottom = _scrollController.position.pixels >=
          _scrollController.position.maxScrollExtent - 50;
      if (_autoScroll != isAtBottom) {
        setState(() {
          _autoScroll = isAtBottom;
        });
      }
    }
  }

  void _updateCachedLogs() {
    // 从设置中获取日志级别，并应用过滤
    final settings = Provider.of<SettingsProvider>(context, listen: false);
    final minLevel = settings.logLevel;
    
    _cachedFilteredLogs = _logService.getFilteredLogs(
      level: _filterLevel,
      category: _filterCategory,
    ).where((log) {
      // 根据设置的最小级别过滤
      return _shouldShowLog(log.level, minLevel);
    }).toList();
  }
  
  // 判断是否应该显示某个级别的日志
  bool _shouldShowLog(LogLevel logLevel, LogLevel minLevel) {
    final levels = [LogLevel.error, LogLevel.warning, LogLevel.info, LogLevel.debug];
    final logIndex = levels.indexOf(logLevel);
    final minIndex = levels.indexOf(minLevel);
    return logIndex <= minIndex; // 级别小于等于设置的最小级别时显示
  }

  List<LogEntry> get _filteredLogs => _cachedFilteredLogs;

  @override
  Widget build(BuildContext context) {
    final l10n = AppLocalizations.of(context);
    final settings = Provider.of<SettingsProvider>(context);

    return Scaffold(
      appBar: AppBar(
        title: Text(l10n.translate('feature_connection_log')),
        actions: [
          // 当前日志级别指示器
          Center(
            child: Container(
              margin: const EdgeInsets.only(right: 8),
              padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
              decoration: BoxDecoration(
                color: _getLogColor(settings.logLevel).withOpacity(0.2),
                borderRadius: BorderRadius.circular(16),
                border: Border.all(
                  color: _getLogColor(settings.logLevel),
                  width: 1,
                ),
              ),
              child: Text(
                _getLogLevelText(settings.logLevel),
                style: TextStyle(
                  fontSize: 12,
                  color: _getLogColor(settings.logLevel),
                  fontWeight: FontWeight.bold,
                ),
              ),
            ),
          ),
          IconButton(
            icon: const Icon(Icons.delete_outline),
            onPressed: () {
              _showClearConfirmDialog(context, l10n);
            },
            tooltip: l10n.translate('action_clear'),
          ),
          IconButton(
            icon: const Icon(Icons.file_download),
            onPressed: () {
              _exportLogs(context, l10n);
            },
            tooltip: l10n.translate('action_export'),
          ),
        ],
      ),
      body: Column(
        children: [
          // 过滤器
          Container(
            padding: const EdgeInsets.all(16),
            decoration: BoxDecoration(
              color: Colors.white,
              boxShadow: [
                BoxShadow(
                  color: Colors.black.withOpacity(0.05),
                  blurRadius: 4,
                  offset: const Offset(0, 2),
                ),
              ],
            ),
            child: SingleChildScrollView(
              scrollDirection: Axis.horizontal,
              child: Row(
                children: [
                  _buildFilterChip(null, 'All', Icons.list, Colors.grey),
                  const SizedBox(width: 8),
                  _buildFilterChip(LogLevel.info, 'Info', Icons.info_outline, Colors.blue),
                  const SizedBox(width: 8),
                  _buildFilterChip(LogLevel.warning, 'Warning', Icons.warning_amber, Colors.orange),
                  const SizedBox(width: 8),
                  _buildFilterChip(LogLevel.error, 'Error', Icons.error_outline, Colors.red),
                  const SizedBox(width: 8),
                  _buildFilterChip(LogLevel.debug, 'Debug', Icons.bug_report, Colors.purple),
                ],
              ),
            ),
          ),

          // 日志列表
          Expanded(
            child: Stack(
              children: [
                _filteredLogs.isEmpty
                    ? Center(
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            Icon(
                              Icons.description_outlined,
                              size: 80,
                              color: Colors.grey.shade300,
                            ),
                            const SizedBox(height: 16),
                            Text(
                              'No logs available',
                              style: TextStyle(
                                fontSize: 16,
                                color: Colors.grey.shade600,
                              ),
                            ),
                            const SizedBox(height: 8),
                            Text(
                              'Logs will appear here when VPN connects',
                              style: TextStyle(
                                fontSize: 12,
                                color: Colors.grey.shade400,
                              ),
                            ),
                          ],
                        ),
                      )
                    : ListView.builder(
                        controller: _scrollController,
                        padding: const EdgeInsets.all(16),
                        itemCount: _filteredLogs.length,
                        // 使用 itemExtent 提升性能
                        itemExtent: null,
                        // 添加缓存范围，减少重建
                        cacheExtent: 500,
                        itemBuilder: (context, index) {
                          // 使用 RepaintBoundary 隔离重绘
                          return RepaintBoundary(
                            child: _buildLogItem(_filteredLogs[index]),
                          );
                        },
                      ),
                
                // 自动滚动按钮
                if (!_autoScroll && _filteredLogs.isNotEmpty)
                  Positioned(
                    right: 16,
                    bottom: 16,
                    child: FloatingActionButton.small(
                      onPressed: () {
                        _scrollController.animateTo(
                          _scrollController.position.maxScrollExtent,
                          duration: const Duration(milliseconds: 300),
                          curve: Curves.easeOut,
                        );
                      },
                      backgroundColor: Colors.blue,
                      child: const Icon(Icons.arrow_downward, size: 20),
                    ),
                  ),
                
                // 日志计数指示器
                if (_filteredLogs.isNotEmpty)
                  Positioned(
                    left: 16,
                    bottom: 16,
                    child: Container(
                      padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
                      decoration: BoxDecoration(
                        color: Colors.black.withOpacity(0.7),
                        borderRadius: BorderRadius.circular(20),
                      ),
                      child: Text(
                        '${_filteredLogs.length} log${_filteredLogs.length > 1 ? 's' : ''}',
                        style: const TextStyle(
                          color: Colors.white,
                          fontSize: 12,
                        ),
                      ),
                    ),
                  ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildFilterChip(LogLevel? level, String label, IconData icon, Color color) {
    final isSelected = _filterLevel == level;
    return FilterChip(
      selected: isSelected,
      label: Row(
        mainAxisSize: MainAxisSize.min,
        children: [
          Icon(icon, size: 16, color: isSelected ? Colors.white : color),
          const SizedBox(width: 4),
          Text(label),
        ],
      ),
      onSelected: (selected) {
        setState(() {
          _filterLevel = selected ? level : null;
          _updateCachedLogs();
        });
      },
      selectedColor: color,
      checkmarkColor: Colors.white,
      backgroundColor: color.withOpacity(0.1),
    );
  }

  Widget _buildLogItem(LogEntry log) {
    return Card(
      margin: const EdgeInsets.only(bottom: 8),
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(12),
        side: BorderSide(color: _getLogColor(log.level).withOpacity(0.3)),
      ),
      child: InkWell(
        onLongPress: () {
          final logText = '[${log.level.name.toUpperCase()}] ${_formatTime(log.time)} - ${log.message}';
          Clipboard.setData(ClipboardData(text: logText));
          ScaffoldMessenger.of(context).showSnackBar(
            const SnackBar(
              content: Text('Log copied to clipboard'),
              behavior: SnackBarBehavior.floating,
              duration: Duration(seconds: 1),
            ),
          );
        },
        borderRadius: BorderRadius.circular(12),
        child: Padding(
          padding: const EdgeInsets.all(12),
          child: Row(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Container(
                padding: const EdgeInsets.all(8),
                decoration: BoxDecoration(
                  color: _getLogColor(log.level).withOpacity(0.1),
                  shape: BoxShape.circle,
                ),
                child: Icon(
                  _getLogIcon(log.level),
                  size: 16,
                  color: _getLogColor(log.level),
                ),
              ),
              const SizedBox(width: 12),
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Row(
                      children: [
                        Text(
                          log.level.name.toUpperCase(),
                          style: TextStyle(
                            fontSize: 11,
                            fontWeight: FontWeight.bold,
                            color: _getLogColor(log.level),
                          ),
                        ),
                        if (log.category != null) ...[
                          const SizedBox(width: 8),
                          Container(
                            padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
                            decoration: BoxDecoration(
                              color: Colors.grey.shade200,
                              borderRadius: BorderRadius.circular(4),
                            ),
                            child: Text(
                              log.category!,
                              style: TextStyle(
                                fontSize: 10,
                                color: Colors.grey.shade700,
                              ),
                            ),
                          ),
                        ],
                        const Spacer(),
                        Text(
                          _formatTime(log.time),
                          style: TextStyle(
                            fontSize: 11,
                            color: Colors.grey.shade600,
                          ),
                        ),
                      ],
                    ),
                    const SizedBox(height: 4),
                    Text(
                      log.message,
                      style: const TextStyle(fontSize: 13),
                    ),
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  Color _getLogColor(LogLevel level) {
    switch (level) {
      case LogLevel.info:
        return Colors.blue;
      case LogLevel.warning:
        return Colors.orange;
      case LogLevel.error:
        return Colors.red;
      case LogLevel.debug:
        return Colors.purple;
    }
  }

  IconData _getLogIcon(LogLevel level) {
    switch (level) {
      case LogLevel.info:
        return Icons.info_outline;
      case LogLevel.warning:
        return Icons.warning_amber;
      case LogLevel.error:
        return Icons.error_outline;
      case LogLevel.debug:
        return Icons.bug_report;
    }
  }

  String _formatTime(DateTime time) {
    final now = DateTime.now();
    final diff = now.difference(time);

    if (diff.inSeconds < 60) {
      return '${diff.inSeconds}s ago';
    } else if (diff.inMinutes < 60) {
      return '${diff.inMinutes}m ago';
    } else if (diff.inHours < 24) {
      return '${diff.inHours}h ago';
    } else {
      return '${time.hour.toString().padLeft(2, '0')}:${time.minute.toString().padLeft(2, '0')}';
    }
  }
  
  String _getLogLevelText(LogLevel level) {
    switch (level) {
      case LogLevel.error:
        return '错误';
      case LogLevel.warning:
        return '警告';
      case LogLevel.info:
        return '信息';
      case LogLevel.debug:
        return '调试';
    }
  }

  void _showClearConfirmDialog(BuildContext context, AppLocalizations l10n) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: Text(l10n.translate('action_clear')),
        content: const Text('Are you sure you want to clear all logs?'),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: Text(l10n.translate('action_cancel')),
          ),
          TextButton(
            onPressed: () {
              _logService.clear();
              setState(() {
                _updateCachedLogs();
              });
              Navigator.pop(context);
              ScaffoldMessenger.of(context).showSnackBar(
                const SnackBar(
                  content: Text('Logs cleared'),
                  behavior: SnackBarBehavior.floating,
                ),
              );
            },
            child: Text(
              l10n.translate('action_confirm'),
              style: const TextStyle(color: Colors.red),
            ),
          ),
        ],
      ),
    );
  }

  void _exportLogs(BuildContext context, AppLocalizations l10n) {
    final logsText = _logService.exportLogs(
      level: _filterLevel,
      category: _filterCategory,
    );

    Clipboard.setData(ClipboardData(text: logsText));
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text('${_filteredLogs.length} logs exported to clipboard'),
        behavior: SnackBarBehavior.floating,
        action: SnackBarAction(
          label: 'OK',
          onPressed: () {},
        ),
      ),
    );
  }
}